//
//  SpriteKitMainViewController+Monitor.swift
//  SpriteKitDemo
//
//  Created by lizhijun on 2023/4/21.
//

import Foundation
import UIKit
import SpriteKit
extension SKMainScene{
    
    override func update(_ currentTime: TimeInterval) {
        
        let nodes = self.nodeArray
        for node in nodes{
            if let node = node as? AJSpriteNode {
                if node.contentView?.superview == nil,let contentView = node.contentView{
                   
                    self.contentView.addSubview(contentView)
                }
                
                let positon = self.convertPoint(toView: node.position)
                node.contentView?.AJCenterX = positon.x
                node.contentView?.AJCenterY = positon.y
            }
        }
    }
    
    override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
        for touch in touches {
            var location = touch.location(in: self)
            guard let playerRole = playerRole else {return}
            location = convert(location, to: self)
            // 超出屏幕
            if location.x >= self.size.width - (playerRole.size.width / 2) {
                location.x = self.size.width - (playerRole.size.width / 2)
            } else if location.x <= (playerRole.size.width / 2) {
                location.x = playerRole.size.width / 2
            }

            if location.y >= self.size.height - (playerRole.size.height / 2) {
                location.y = self.size.height - (playerRole.size.height / 2)
            } else if location.y <= (playerRole.size.height / 2) {
                location.y = (playerRole.size.height / 2)
            }

            let action = SKAction.move(to: CGPoint(x: location.x, y: location.y), duration: 0.1)
            playerRole.run(action)
        }
    }
    
}
